import { shopcart_add, shopcart_clear, shopcart_list, shopcart_sub } from "@/utils/api"
import store from "..";

export default{
    namespaced:true,
    state:{
        shopcartlist:[],
    },
    mutations:{
        save_shopcartlist(state,payload){
            state.shopcartlist=payload;
        },
        clear_shopcartlist(state){
            state.shopcartlist=[];
        },
        add_shopgoodsnum(state,payload){
            var index=state.shopcartlist.findIndex((item)=>{
                return item.id==payload.id;
            });
            if(index!=-1){
                state.shopcartlist[index].count++;
            }else{
                var goods=JSON.parse(JSON.stringify(payload));
                goods.count=1;
                state.shopcartlist.push(goods);
            }
        },
        sub_shopgoodsnum(state,payload){
            var index=state.shopcartlist.findIndex((item)=>{
                return item.id==payload.id;
            });
            if(state.shopcartlist[index].count!=1){
                state.shopcartlist[index].count--;
            }else{
                state.shopcartlist.splice(index,1);
            }
        }
    },
    actions:{
        request_shopcartlist(store){
            var userid=JSON.parse(localStorage.getItem('userinfo')).id;
            shopcart_list({userid}).then((res)=>{
                if(res.data.code==200){
                    store.commit('save_shopcartlist',res.data.list);
                }
            })
        },
        shopcart_clear(store){
            var userid=JSON.parse(localStorage.getItem('userinfo')).id;
            shopcart_clear({userid}).then((res)=>{
                if(res.data.code==200){
                    store.commit('clear_shopcartlist');
                }
            })
        },
        request_shopcartlist_add(store,payload){
            var userid=JSON.parse(localStorage.getItem('userinfo')).id;
            shopcart_add({userid,goodid:payload.id}).then((res)=>{
                if(res.data.code==200){
                    store.commit('add_shopgoodsnum',payload);
                }
            })
        },
        request_shopcartlist_sub(store,payload){
            var userid=JSON.parse(localStorage.getItem('userinfo')).id;
            shopcart_sub({userid,goodid:payload.id}).then((res)=>{
                if(res.data.code==200){
                    store.commit('sub_shopgoodsnum',payload);
                }
            })
        }
    },

}